package com.api.aiyh_pcn.fadada.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import org.h2.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.aiyh_pcn.fadada.dao.FaDDServiceMapping;
import com.api.aiyh_pcn.fadada.service.impl.FaDDServiceImpl;

import aiyh.utils.ApiResult;
import aiyh.utils.Util;
import aiyh.utils.mapUtil.ParaMap;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.zwl.common.ToolUtil;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import weaver.conn.RecordSet;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

/**
 * @author EBU7-dev1-ayh
 * @create 2021/9/28 0028 16:05 法大大相关接口
 */
@Path("/fadada")
public class FaDDController {
    private final FaDDServiceImpl faDDService = new FaDDServiceImpl();
    private final FaDDServiceMapping faDDServiceMapping = new FaDDServiceMapping();
    private final ToolUtil toolUtil = new ToolUtil();

    /**
     * 查询配置信息
     *
     * @param workflowId
     *            流程id
     * @return 配置信息
     */
    @GET
    @Path("/getConfig/{workflowId}")
    public String getConfig(@PathParam("workflowId") String workflowId) {
        try {
            Map<String, Object> configParam = faDDService.getConfigParam(workflowId);
            return ApiResult.success(configParam);
        } catch (Exception e) {
            return ApiResult.error(e.toString());
        }
    }

    /**
     * 验证企业签署状态
     *
     * @param params
     *            查验参数
     * @return 企业验证的状态
     */
    @Path("/signature")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String checkCertification(@RequestBody Map<String, Object> params) {
        try {
            Map<String, Object> certificationResult = faDDService.checkCertification(params);
            return ApiResult.success(certificationResult);
        } catch (Exception e) {
            return ApiResult.error(e.toString());
        }
    }

    /**
     * 催一催
     *
     * @param workflowId
     *            流程id
     * @param requestId
     *            请求id
     * @return 催一催
     */
    @Path("/signedContract/{languageGroupId}/{requestId}/{workflowId}")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String signedContract(@Context HttpServletRequest request, @Context HttpServletResponse response,
        @PathParam("workflowId") String workflowId, @PathParam("requestId") String requestId,
        @PathParam("languageGroupId") int languageGroupId) {
        User user = HrmUserVarify.getUser(request, response);
        try {
            faDDService.queryContractStatus(workflowId, requestId, 0);
            Map<String, String> language = Util.queryLanguage(languageGroupId, user.getLanguage());
            String info = language.get("rushInfo");
            return ApiResult.success(info);
        } catch (Exception e) {
            toolUtil.writeErrorLog("错误：" + e);
            return ApiResult.error(e.toString());
        }
    }

    /**
     * 本方签署
     *
     * @param workflowId
     *            流程id
     * @param requestId
     *            请求id
     * @return 本方签署结果
     */
    @Path("/signedContract/own/{languageGroupId}/{requestId}/{workflowId}")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String signedContractOwn(@Context HttpServletRequest request, @Context HttpServletResponse response,
        @PathParam("workflowId") String workflowId, @PathParam("requestId") String requestId,
        @PathParam("languageGroupId") int languageGroupId) {
        User user = HrmUserVarify.getUser(request, response);
        try {
            faDDService.signedContractOwn(workflowId, requestId);
            String mainTable = faDDServiceMapping.getMainTable(workflowId);
            // TODO 更新本方签署
            PrepSqlResultImpl sqlResult =
                Util.createSqlBuilder().updateSql(mainTable, ParaMap.create().put("signed_oneself", 1),
                    Util.createPrepWhereImpl().whereAnd("requestid").whereEqual(requestId));
            RecordSet rs = new RecordSet();
            rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
            Map<String, String> language = Util.queryLanguage(languageGroupId, user.getLanguage());
            String info = language.get("contractSignedInfo");
            return ApiResult.success(info);
        } catch (Exception e) {
            toolUtil.writeErrorLog("错误：" + e.toString());
            return ApiResult.error(e.toString());
        }
    }

    /**
     * 合同下载
     *
     * @param requestId
     *            请求id
     * @return 合同问价压缩包
     */
    @Path("/contract/download/{workflowId}/{requestId}")
    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response contractDownload(@PathParam("requestId") String requestId,
        @PathParam("workflowId") String workflowId) {
        toolUtil.writeErrorLog("进入请求方法，获取到请求id：" + requestId);
        try {
            StreamingOutput contractZipStream = faDDService.contractDownload(requestId, workflowId);
            return Response.ok(contractZipStream, MediaType.APPLICATION_OCTET_STREAM).type("application/zip")
                .header("Content-Disposition", "attachment;filename=contracts.zip").build();
        } catch (Exception e) {
            toolUtil.writeErrorLog("转换失败，" + e.toString());
            return Response.ok(ApiResult.error("出现错误，错误原因: " + e), MediaType.APPLICATION_JSON).build();
        }
    }

    /**
     * 获取流程全版本
     *
     * @param workflowId
     *            流程id
     * @return 流程全版本id
     */
    @Path("/getAllVersion/{workflowId}/{markOnly}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getAllVersion(@PathParam("workflowId") String workflowId, @PathParam("markOnly") String markOnly) {
        try {
            Map<String, Object> allVersion = faDDService.getAllVersion(workflowId, markOnly);
            return ApiResult.success(allVersion);
        } catch (Exception e) {
            toolUtil.writeErrorLog("错误：" + e.toString());
            return ApiResult.error(e.toString());
        }
    }

    /**
     * 查验是否全部签订完毕
     *
     * @param requestId
     *            请求id
     * @return 查验结果
     */
    @Path("/isAllSigned/{workflowId}/{requestId}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String isAllSinged(@PathParam("requestId") String requestId, @PathParam("workflowId") String workflowId) {
        try {
            faDDService.queryContractStatus(workflowId, requestId, 1);
            boolean isAllSinged = faDDService.isAllSinged(requestId, workflowId);
            boolean isSingedOneself = faDDService.isSingedOneself(requestId, workflowId);
            Map<String, Object> result =
                ParaMap.create().put("isAllSinged", isAllSinged).put("isSingedOneself", isSingedOneself);
            return ApiResult.success(result);
        } catch (Exception e) {
            toolUtil.writeErrorLog("错误：" + e);
            return ApiResult.error(e.toString());
        }
    }

    @Path("/getLanguage/{languageGroupId}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getLanguage(@Context HttpServletRequest request, @Context HttpServletResponse response,
        @PathParam("languageGroupId") int languageGroupId) {
        User user = HrmUserVarify.getUser(request, response);
        Map<String, String> map = Util.queryLanguage(languageGroupId, user.getLanguage());
        return ApiResult.success(map);
    }

    @Path("/callback/signed")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String callBackSigned(@RequestBody Map<String, Object> params) {
        toolUtil.writeErrorLog("回调方法：" + JSONObject.toJSONString(params));
        Map<String, Object> result = new HashMap<>();
        String bizContent = String.valueOf(params.get("bizContent"));
        if (StringUtils.isNullOrEmpty(bizContent)) {
            toolUtil.writeErrorLog("参数没获取到！");
            result.put("code", "200");
            result.put("msg", "操作失败！");
            return JSONObject.toJSONString(result);
        }
        byte[] decode = Base64.getDecoder().decode(bizContent.getBytes(StandardCharsets.UTF_8));
        String decodeStr = null;
        try {
            decodeStr = new String(decode, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String jsonStr = null;
        try {
            jsonStr = URLDecoder.decode(decodeStr, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String resultCode = String.valueOf(jsonObject.getString("resultCode"));
        String docNo = String.valueOf(jsonObject.getString("docNo"));
        if (!"1".equals(resultCode)) {
            toolUtil.writeErrorLog("重复签署合同！" + docNo);
        }
        // Util.createSqlBuilder().updateSql()

        this.toolUtil.writeErrorLog(jsonObject.toJSONString());
        result.put("code", "200");
        result.put("msg", "操作成功！");
        return JSONObject.toJSONString(result);
    }
}
